/**
 * H5 WebSocket
 */
import { getStore } from '@/libs/store'
import SockJS from 'sockjs-client'
import Stomp from 'stompjs'
import { Notification, MessageBox, Message } from 'element-ui'
import DingdongSound from '@/assets/audio/dingdong.mp3'


/**
 * 连接 Socket
 */
let stomp
const initWebsocket = () => {
    const user = getStore({
        name: 'USER'
    })

    let sock = new SockJS(process.env.VUE_APP_WS_URL)
    stomp = Stomp.over(sock);
    stomp.debug = true; //调试模式
    stomp.connect({}, function(frame) {
        console.log('==================== WebSocket 连接成功 ====================')

        //订阅消息(用于连接到WebSocket后返回的消息)
        stomp.subscribe('/notification', function(response) {
            showMessage('success', '', response.body)
        })

        subscribeoNtification()
    }, function() {
        console.log('******************** WebSocket 连接失败 ********************')
        showMessage('error', '', 'WebSocket 连接失败')
    });
}

/**
 * 监听订阅消息
 */
const subscribeoNtification = () => {
    stomp.subscribe('/topic/notification', function(response) {
        const data = JSON.parse(response.body)
        document.getElementById('sound').src = DingdongSound

        if(data.type === 'broadcast' && data.mode === 'Message') {
            showMessage('success', data.title, data.message)
        } else if(data.type === 'broadcast' && data.mode === 'MessageBox') {
            showMessageBox('success', data.title, data.message)
        } else {
            showNotification('success', data.title, data.message)
        }
    })
}

const showNotification = (type='success', title, message) => {
    Notification({
        type: type,
        duration: 2000,
        title: title,
        message: message
    })
}

const showMessageBox = (type='success', title, message) => {
    MessageBox({
        type: type,
        title: title,
        message: message,
        customClass: 'errorMessageBox'
    })
}

const showMessage = (type='success', title, message) => {
    Message({
        type: type,
        duration: 2000,
        message: message
    })
}

export default initWebsocket ;